package com.exp.security.config.sms;

import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.util.Assert;

import java.io.Serial;
import java.util.Collection;

/**
 * @author zhangxj
 * @date 2025/1/7
 * @Description 用于封装手机号验证登录的认证信息
 */
public class SmsAuthenticationToken extends AbstractAuthenticationToken {
    @Serial
    private final static long serialVersionUID = 1L;
    private final Object principal;
    private Object credentials;

    public SmsAuthenticationToken(Object principal, Object credentials, Collection<? extends GrantedAuthority> authorities) {
        super(authorities);
        this.principal = principal;
        this.credentials = credentials;
        super.setAuthenticated(true);
    }

    public SmsAuthenticationToken(Object principal, Object credentials) {
        super(null);
        this.principal = principal;
        this.credentials = credentials;
        this.setAuthenticated(false);
    }

    /**
     * 创建未认证的token
     * @param principal 手机号
     * @param credentials 验证码
     * @return SmsAuthenticationToken 对象
     */
    public static SmsAuthenticationToken unauthenticated(Object principal, Object credentials) {
        return new SmsAuthenticationToken(principal, credentials);
    }

    /**
     * 创建已认证的token
     * @param principal 手机
     * @param credentials 验证码
     * @param authorities 权限集合
     * @return SmsAuthenticationToken 对象
     */
    public static SmsAuthenticationToken authenticated(Object principal, Object credentials,
                                                                    Collection<? extends GrantedAuthority> authorities) {
        return new SmsAuthenticationToken(principal, credentials, authorities);
    }


    @Override
    public Object getCredentials() {
        return this.credentials;
    }

    @Override
    public Object getPrincipal() {
        return this.principal;
    }

    @Override
    public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
        Assert.isTrue(!isAuthenticated,
                "Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
        super.setAuthenticated(false);
    }

    @Override
    public void eraseCredentials() {
        super.eraseCredentials();
        this.credentials = null;
    }

}
